﻿using System;
using Reactor.Environment;
using Reactor.Messages.Commands.Core;
using Reactor.Messaging;
using Reactor.Messaging.Attributes;
using Reactor.ServiceGrid;

namespace Reactor.CoreHost.Handlers
{
    [PointToPointChannel]
    public class ShutdownServiceCommandHandler : MessageHandlerBase<ShutdownService>
    {
        #region Overrides of MessageHandlerBase<ShutdownService>

        public override void OnHandling(ShutdownService message, IMessageContext messageContext)
        {
            AssertThatCurrentServiceIsAReactorCore();

            if(message.CoreName != Context.GridContext.CurrentReactorService.Identifier.Name) return;

            var core = (IReactorCore)Context.GridContext.CurrentReactorService;

            try
            {
                // Instruct core to shutdown this service
                core.ShutdownService(new ServiceIdentifier { Name = message.ServiceName, Version = new Version(message.ServiceVersion) });
            }
            catch (InvalidOperationException e)
            {
                Log.Error("ReactorCore threw an exception when ShutdownService was called.", e);
            }
        }

        #endregion
    }
}
